// ==UserScript==
// @name           FedLoggerHacker
// @namespace      jirina42@seznam.cz
// @description    Allows pilots to easily submit hack logs to the Federation logger
// @include        http*://orion.pardus.at/hack.php*
// @version        1.3
// ==/UserScript==

var serverURL = "http://federation.fedfalcons.com/";
//unsafeWindow.serverURL = serverURL;

function ALOGsaveHack() {
    function prepareHack(hack) {
        function prepareSector(pos, sector) {
                var i = sector.indexOf("[");
                if (i != -1) {
                        pos.sector = sector.substr(0, i - 1);
                        pos.coords = sector.substr(i);
                } else
                        pos.sector = sector;
        }

        function getPosition(posCell) {
                var len = posCell.childNodes.length;
                var result = {sector: null, coords: null};
                result.cluster = posCell.childNodes[len - 1].textContent;
                if (len > 1)
                        prepareSector(result, posCell.childNodes[0].nodeValue);
                return result;
        }

        function prepareResources(resourceCell) {
                var result = [];
                var res = null;
                for (var i = 0; i < resourceCell.childNodes.length; i++) {
                        var node = resourceCell.childNodes[i];
                        var tag = node.tagName;
                        if (tag) {
                                if (tag.toLowerCase() == "br")
                                        continue;
                                else
                                if (tag.toLowerCase() == "img") {
                                        var name = node.src;
                                        name = name.substr(name.lastIndexOf("/") + 1);
                                        //res = {img_name: name};
                                        res = {img: name}; // For backwards compatibility with older Infocentre version
                                }
                        }
                        else {
                                var amount = node.nodeValue;
                                res.amount = amount.substring(amount.indexOf(" ") + 1, amount.length - 1);
                                result.push(res);
                        }
                }
                return result;
        }

        // if the user has no buildings, the buildings table is not displayed...
        // we have to substitute this if it's not there so that data doesn't get
        // truncated; this operates for the table number provided as the index
        function fixBuildings(tables, index) {
                if (tables.length > index) {
                        var buildingsTH = tables[index].getElementsByTagName("th")[0];
                        // if not buildings table
                        if (!buildingsTH || buildingsTH.innerHTML != "Buildings") {
                                var newTables = tables.slice(0, index);
                                newTables[index] = null;
                                for (var i = index; i < tables.length; i++) {
                                        newTables[i+1] = tables[i];
                                }
                                tables = newTables;
                        }
                }
                return tables;
        }
    
        var str = document.location.hostname;
        var universe = str.substring(0, str.indexOf("."));
        if (!universe)
            universe = "orion";
        hack.universe = universe.charAt(0).toUpperCase() + universe.substring(1);
        
        var table = document.getElementsByTagName("table")[0];
        table = table.rows[1].cells[1].getElementsByTagName("table")[0];
        var cell = table.rows[0].cells[0];
        var tables = [];
        for (var i = 0; i < cell.childNodes.length; i++) {
                var child = cell.childNodes[i];
                var tag = child.tagName;
                if (tag && (tag.toLowerCase() == "table"))
                        tables.push(child);
        }
        hack.location = table.getElementsByTagName("a")[0].innerHTML;
    
        var buildingTable = null;
        var foeTable = null;
        var friendTable = null;
        var resourceTable = null;
        var shipTable = null;
        var turnoverOffset = 0;

        // fix the buildings table
        switch (tables.length) {
        case 3:
        case 4:
        case 5:
                // tables[2] will be the buildings table
                tables = fixBuildings(tables, 2);
                break;
        case 6:
        case 7:
        case 8:
        case 9:
        case 10: // many buildings possible
                // tables[3] will be the buildings table
                tables = fixBuildings(tables, 3);
                break;
        }
    
        // classify which type of hack it is
        switch (tables.length) {
            case 2:
                // either trade or brute
                var thText = tables[1].getElementsByTagName("th")[0].innerHTML;
                if(
                        thText.match(/^Last transactions at /) ||
                        thText.match(/'s last own transactions$/)
                ) {
                        hack.method = "trade";
                } else {
                        hack.method = "brute";
                }
                break;
            case 4:
                hack.method = "skilled";
                buildingTable = tables[2];
                foeTable = tables[3];
                break;
            case 5:
                hack.method = "freak";
                buildingTable = tables[2];
                foeTable = tables[3].getElementsByTagName("table")[0];
                friendTable = tables[3].getElementsByTagName("table")[1];
                resourceTable = tables[4];
                turnoverOffset = 2;
                break;
            case 6:
            case 7:
            case 8:
            case 9:
            case 10: // many buildings possible
                    hack.method = "guru";
                    shipTable = tables[2];
                    buildingTable = tables[3];
                    foeTable = tables[4].getElementsByTagName("table")[0];
                    friendTable = tables[4].getElementsByTagName("table")[1];
                    resourceTable = tables[5];
                    turnoverOffset = 2;
                    break;
            default:
                return false;
        }
    
        // not all hacks are pilot related
        var doPilotSearch = true;

        // trade hack
        if (hack.method == "trade") {
                var tradeTable = tables[1];
                hack.date = new Date(tradeTable.rows[2].cells[0].innerHTML.replace(/-/g, "/")).getTime();

                var thText = tables[1].getElementsByTagName("th")[0].innerHTML;
                // pilot trade hack
                if (thText.match(/'s last own transactions$/)) {
                        hack.pilot = thText.replace(/'s last own transactions$/, '');
                } else {
                        // skip pilot search since it's not a pilot that was hacked
                        doPilotSearch = false;

                        // get location and position of hacked structure
                        hack.location = thText.replace(/^Last transactions at /,'');
                        var structure = tables[1].rows[2].cells[1].innerHTML;
                        var pos = structure.replace(/^.*\(([^\)]+)\)$/, '$1');
                        hack.position = {};
                        hack.position.sector = pos.replace(/^(.*) [^ ]+$/, '$1');
                        hack.position.coords = "[" + pos.replace(/^.* ([^ ]+)$/, '$1') + "]";
                }

                // each transaction is stored in the buildings fields
                hack.building_amount = tables[1].rows.length-2;
                hack.buildings = [];
                for (var i = 0; i < hack.building_amount; i++) {
                        var transaction = {};
                        var hackRow = tables[1].rows[i+2];
                        transaction.date = new Date(hackRow.cells[0].innerHTML.replace(/-/g, "/")).getTime();
                        transaction.position = hackRow.cells[1].innerHTML;
                        var pilot = hackRow.cells[2].innerHTML;
                        transaction.pilot = pilot.replace(/^.*>(.*)<.*$/, '$1');
                        transaction.direction = hackRow.cells[3].innerHTML;
                        transaction.commodity = hackRow.cells[4].innerHTML;
                        transaction.amount = hackRow.cells[5].innerHTML;
                        transaction.average = hackRow.cells[6].innerHTML;
                        transaction.total = hackRow.cells[7].innerHTML;

                        // convert the img fields to be forced to be links to Pardus;
                        // this is for people who use local image packs
                        transaction.commodity = transaction.commodity.replace(
                                /src=".*\/([^\/]+)/,
                                'src="http://static.pardus.at/img/stdhq/res/$1'
                        );
                        transaction.average = transaction.average.replace(
                                /src=".*\/credits.png/,
                                'src="http://static.pardus.at/img/stdhq/credits.png'
                        );
                        transaction.total = transaction.total.replace(
                                /src=".*\/credits.png/,
                                'src="http://static.pardus.at/img/stdhq/credits.png'
                        );
                        hack.buildings.push(transaction);
                }

        // any pilot hack
        } else {
                var pilotTable = tables[1];
                hack.date = new Date(pilotTable.rows[0].cells[0].innerHTML.replace(/-/g, "/")).getTime();
                hack.pilot = pilotTable.rows[1].cells[0].textContent;
                hack.credits = pilotTable.rows[3].cells[0].innerHTML.replace(/,/g, "");
                hack.reputation = pilotTable.rows[3].cells[1].innerHTML.replace(/,/g, "");
                hack.building_amount = pilotTable.rows[3].cells[2].innerHTML;
                if (pilotTable.rows.length >= 6)
                        //hack.experience = pilotTable.rows[5].cells[0].innerHTML.replace(/,/g, "");
                        hack.experience = pilotTable.rows[5 + turnoverOffset].cells[0].innerHTML.replace(/,/g, "");
                if (pilotTable.rows.length >= 8)
                        //hack.position = getPosition(pilotTable.rows[7].cells[0]);
                        hack.position = getPosition(pilotTable.rows[7 + turnoverOffset].cells[0]);
                if (pilotTable.rows.length >= 9) {
                        hack.turnover = pilotTable.rows[5].cells[0].innerHTML.replace(/,/g, "");
                }
        }


        if (doPilotSearch) {
                var lookupCell = tables[0].rows[1].cells[0];
                var pilotSelect = lookupCell.getElementsByTagName("select")[0];
                if (pilotSelect) {
                        for (var i = 0; i < pilotSelect.length; i++) {
                                var option = pilotSelect.item(i);
                                if (option.text == hack.pilot) {
                                        hack.pilot_id = option.value;
                                        break;
                                }
                        }
                } else {
                        var pilotInput = lookupCell.getElementsByTagName("input")[1];
                        hack.pilot_id = pilotInput.value;
                }
        }

        
        if (shipTable != null) {
            hack.ship_status = {};
            for (var i = 1; i < shipTable.rows.length; i++) {
                var font = shipTable.rows[i].cells[0].getElementsByTagName("font")[0];
                var name = font.innerHTML;
                name = name.substr(0, name.indexOf(":")).toLowerCase();
                var status = {};
                status.color = font.color;
                status.amount = shipTable.rows[i].cells[1].getElementsByTagName("table")[0].width;
                hack.ship_status[name] = status;
            }
        }

        hack.building_positions = [];
        if (buildingTable != null) {
            for (var i = 1; i < buildingTable.rows.length; i++) {
                var pos = getPosition(buildingTable.rows[i].cells[1]);
                pos.amount = buildingTable.rows[i].cells[0].innerHTML;
                hack.building_positions.push(pos);
            }
        }
    
        hack.foes = [];
        hack.foe_alliances = [];
        var alliance = false;
        if (foeTable != null) {
            for (var i = 1; i < foeTable.rows.length; i++) {
                var cell = foeTable.rows[i].cells[0];
                if (cell.tagName.toLowerCase() == "th") {
                    alliance = true;
                    continue;
                }
                if (alliance)
                    hack.foe_alliances.push(cell.textContent);
                else
                    hack.foes.push(cell.textContent);
            }
        }
    
        hack.friends = [];
        hack.friend_alliances = [];
        alliance = false;
        if (friendTable != null) {
            for (var i = 1; i < friendTable.rows.length; i++) {
                var cell = friendTable.rows[i].cells[0];
                if (cell.tagName.toLowerCase() == "th") {
                    alliance = true;
                    continue;
                }
                if (alliance)
                    hack.friend_alliances.push(cell.textContent);
                else
                    hack.friends.push(cell.textContent);
            }
        }
    
        if (resourceTable != null) {
                hack.buildings = [];
                var buildingTables = resourceTable.getElementsByTagName("table");
                for (var i = 0; i < buildingTables.length; i++) {
                        var posStr = buildingTables[i].rows[0].cells[0].innerHTML;
                        posStr = posStr.substr(new String("Building in ").length);
                        var building = {};
                        prepareSector(building, posStr);
                        for (var j = 0; j < hack.building_positions.length; j++) {
                                if (building.sector == hack.building_positions[j].sector) {
                                        building.cluster = hack.building_positions[j].cluster;
                                        break;
                                }
                        }
                        building.commodities = prepareResources(buildingTables[i].rows[2].cells[0]);
                        building.stock = prepareResources(buildingTables[i].rows[2].cells[1]);
                        hack.buildings.push(building);
                }
        }
        return true;
    }

    function objectToXml(obj, nodeName, parentNode) {
        if (!parentNode)
            parentNode = document.implementation.createDocument("", "", null);
        var node = document.createElement(nodeName);
        parentNode.appendChild(node);
        if (obj instanceof Array) {
            var collection = node.ownerDocument.createAttribute("collection");
            collection.value = true;
            node.attributes.setNamedItem(collection);
            var name = nodeName.substr(0, nodeName.length - 1);
            for (var i = 0; i < obj.length; i++)
                objectToXml(obj[i], name, node);
        } else
            if (typeof(obj) == "object") {
                var i;
                for (i in obj)
                objectToXml(obj[i], i, node);
            } else
                node.appendChild(node.ownerDocument.createTextNode(obj));
        return parentNode;
    }

    function xmlToStr(doc) {
        return new XMLSerializer().serializeToString(doc);
    }

    function postHack(data) {
        var username = "C0mbatL0gger"; 
        var password = "vAd9Z7BEt6";
        
        var url = serverURL+"hack_add.php";
        var query =
            "acc="+username
            + "&pwd="+password
            + "&data="+data
            + "&userid="+"9999999"
            + "&uname="+username
            + "&vcode="+"4f188f41e76df1.02180521";
        POajaxPost (url, "POST", query, null);
        document.getElementById ("po_alog_confirm").textContent = "Hack submitted to Federation database. Thank you!";
    }

    var hack = {};
    if (!prepareHack(hack))
        return;
    var doc = objectToXml(hack, "hack");
    postHack(xmlToStr(doc));
}

//unsafeWindow.ALOGsaveHack = ALOGsaveHack;


function POajaxPost (url, method, query, callback) {
   var request = new XMLHttpRequest();
   request.onreadystatechange = function () {
      if (callback) callback (request);
   };
   if(method.toLowerCase() == 'get') url = url+"?"+query;
   request.open(method, url, true);
   request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
   request.send(query);
}
//unsafeWindow.POajaxPost = POajaxPost;

function ALOGchangeCheckbox() {
    localStorage.setItem ("po_alog_submit_logs", String(document.getElementById ('alog_checkbox').checked));
}
//unsafeWindow.ALOGchangeCheckbox = ALOGchangeCheckbox;

function ALOGaddShareBtn() {
    var tbl = document.getElementById ("doHackButton").parentNode.parentNode.parentNode;
    var parent = tbl.parentNode.parentNode;
    localStorage.setItem ("po_alog_submit_logs", "true");
    var div = document.createElement ("tr");
    div.innerHTML = "<td colspan=2 align=center><div style='color:lime;font-size:14px'><input id='alog_checkbox' type='checkbox' checked='true' onclick='ALOGchangeCheckbox();'> submit the hack log automatically to the Federation database</input>\
                    </div><div style='color:lime;font-size:14px' id='po_alog_confirm'></div></td>";
    tbl.appendChild (div);
    
    if (parent.getElementsByTagName ("table").length > 1) {
        // The hack has been performed
        if (localStorage.getItem ("po_alog_submit_logs") == "true") {
            ALOGsaveHack ();
        }
    }
}
//unsafeWindow.ALOGaddShareBtn = ALOGaddShareBtn;

ALOGaddShareBtn();
